//
//  DudsViewController.m
//  BaseFrame
//
//  Created by ENERGY on 2018/5/2.
//  Copyright © 2018年 com.mxh. All rights reserved.
//

#import "DudsViewController.h"
#import "DudsTableViewCell.h"
#import "SelectPicCollectionViewCell.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import "MJPhotoBrowser.h"
#import "MJPhoto.h"
#import <ZYQAssetPickerController/ZYQAssetPickerController.h>
#import "RecycleHistoryViewController.h"
#define TopViewH 50
#define Border 10
#define imageW (SCREEN_WIDTH - 5 * Border)/4
#define bottomBarH 50

@interface DudsViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, TZImagePickerControllerDelegate, MJPhotoBrowserDelegate>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *dataImageArray; // 存储选择的图片（二进制）
@property (nonatomic, strong) NSMutableArray *dataImageWithStrArray; // 上传图片返回的图片地址
@property (nonatomic, strong) NSData *imageWithData;

@property (nonatomic, strong)UIAlertController * alertController;
@property (nonatomic, strong)TZImagePickerController * imagePicker;
@property (nonatomic, strong)UIImagePickerController * imagePickerController;
@property (nonatomic, strong)NSMutableArray * imageArray;

@property (nonatomic, strong)UIView * footerView;
@property (nonatomic, strong)NSArray * dataArry;
@end

@implementation DudsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    
    UIButton * rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60/WIDTH_5S_SCALE, 20/WIDTH_5S_SCALE)];
    [rightBtn addTarget:self action:@selector(rightBarButtonItemClick) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTitle:@"回收历史" forState:UIControlStateNormal];
    [rightBtn setBackgroundColor:[UIColor clearColor]];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightBtn.titleLabel.font = DEF_FontSize_14;
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
}

#pragma init
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = self.footerView;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[DudsTableViewCell class] forCellReuseIdentifier:NSStringFromClass([DudsTableViewCell class])];
    }return _tableView;
}

- (UIView *)footerView{
    if (!_footerView) {
        _footerView = [[UIView alloc] init];
        //上传衣服标题
        UILabel * titleLab = [[UILabel alloc] initWithFrame:CGRectMake(10/WIDTH_5S_SCALE, 0, 100/WIDTH_5S_SCALE, 44/WIDTH_5S_SCALE)];
        titleLab.font = DEF_FontSize_14;
        titleLab.textColor = getColor(textColor);
        titleLab.textAlignment = NSTextAlignmentLeft;
        titleLab.text = @"上传衣服图片";
        [_footerView addSubview:titleLab];
        //collectionView
        int collectionViewH = (SCREEN_WIDTH - 50/WIDTH_5S_SCALE)/4;
        UICollectionViewFlowLayout * layout = [UICollectionViewFlowLayout new];
        layout.sectionInset = UIEdgeInsetsMake(0/WIDTH_5S_SCALE, 10/WIDTH_5S_SCALE, 0/WIDTH_5S_SCALE, 10/WIDTH_5S_SCALE);
        layout.minimumLineSpacing = 10/WIDTH_5S_SCALE;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.itemSize = CGSizeMake(collectionViewH, collectionViewH);
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, titleLab.bottom, SCREEN_WIDTH, collectionViewH) collectionViewLayout:layout];
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;
        self.collectionView.showsHorizontalScrollIndicator = NO;
        self.collectionView.backgroundColor = [UIColor whiteColor];
        [self.collectionView registerClass:[SelectPicCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([SelectPicCollectionViewCell class])];
        [_footerView addSubview:self.collectionView];
        //提交按钮
        int btnX = 20/WIDTH_5S_SCALE;
        int btnH = 35/WIDTH_5S_SCALE;
        int btnW = SCREEN_WIDTH - 2*btnX;
        int btnY = self.collectionView.bottom + 50/WIDTH_5S_SCALE;
        UIButton * submitBtn = [[UIButton alloc] initWithFrame:CGRectMake(btnX, btnY, btnW, btnH)];
        submitBtn.layer.cornerRadius = btnH/2;
        submitBtn.layer.masksToBounds = YES;
        [submitBtn setTitle:@"提交材料" forState:UIControlStateNormal];
        submitBtn.titleLabel.font = DEF_FontSize_14;
        [submitBtn setBackgroundColor:getColor(mainColor)];
        [_footerView addSubview:submitBtn];
        _footerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, submitBtn.bottom + 20);
    }return _footerView;
}


-(UIAlertController *)alertController
{
    if (!_alertController) {
        _alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从图库选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            _imagePicker = [[TZImagePickerController alloc]initWithMaxImagesCount:10 - self.imageArray.count delegate:self];
            _imagePicker.allowPickingVideo = NO;
            _imagePicker.allowTakePicture = NO;
            [self presentViewController:_imagePicker animated:YES completion:nil];
        }];
        UIAlertAction *addPhoneAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:self.imagePickerController animated:YES completion:nil];
            }
            else
            {
                //  [self showMessage:@"当前设备无摄像头，请从相册获取"];
            }
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [photoAction setValue:getColor(@"584f60@") forKey:@"_titleTextColor"];
        [addPhoneAction setValue:getColor(@"584f60@") forKey:@"_titleTextColor"];
        [cancelAction setValue:getColor(@"584f60@") forKey:@"_titleTextColor"];
        [_alertController addAction:photoAction];
        [_alertController addAction:addPhoneAction];
        [_alertController addAction:cancelAction];
    }
    return _alertController;
}

- (NSMutableArray *)dataImageArray
{
    if (!_dataImageArray) {
        _dataImageArray = [NSMutableArray array];
    }
    return _dataImageArray;
}

-(NSMutableArray *)imageArray
{
    if (!_imageArray) {
        _imageArray = [NSMutableArray arrayWithArray:@[[UIImage imageNamed:@"fankui"]]];
    }
    return _imageArray;
}

-(UIImagePickerController *)imagePickerController
{
    if (!_imagePickerController) {
        _imagePickerController = [[UIImagePickerController alloc]init];
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
    }
    return _imagePickerController;
}

- (NSMutableArray *)dataImageWithStrArray
{
    if (!_dataImageWithStrArray) {
        _dataImageWithStrArray = [NSMutableArray array];
    }
    return _dataImageWithStrArray;
}

- (NSArray *)dataArry{
    if (!_dataArry) {
        _dataArry = @[@{@"title":@"联系电话",@"flag":@"0",@"isTextField":@"1",@"placeHolder":@"联系电话"},
                      @{@"title":@"衣服种类",@"flag":@"0",@"isTextField":@"1",@"placeHolder":@"填写衣服种类"},
                      @{@"title":@"选择地址",@"flag":@"1",@"isTextField":@"0",@"placeHolder":@""}];
    }return _dataArry;
}

#pragma mark - UITableView的delegate和datasource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44 / WIDTH_5S_SCALE;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DudsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([DudsTableViewCell class]) forIndexPath:indexPath];
    cell.model = self.dataArry[indexPath.row];
    if (indexPath.row == 2) {
        cell.choosePlace = ^(){
            NSLog(@"跳页");
        };
    }
    return cell;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.imageArray.count < 10) {
        return self.imageArray.count;
    }
    return self.imageArray.count - 1;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SelectPicCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([SelectPicCollectionViewCell class]) forIndexPath:indexPath];
    cell.imageView.image = self.imageArray[indexPath.row];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.imageArray.count < 10) {
        if (indexPath.row == self.imageArray.count - 1) {
            [self presentViewController:self.alertController animated:YES completion:nil];
            return;
        }
    }
    //1.创建图片浏览器
    MJPhotoBrowser *brower = [[MJPhotoBrowser alloc] init];
    //2.告诉图片浏览器显示所有的图片
    NSMutableArray *photos = [NSMutableArray array];
    for (int i = 0 ; i < self.imageArray.count - 1; i++) {
        //传递数据给浏览器
        MJPhoto *mjPhoto = [[MJPhoto alloc] init];
        mjPhoto.image = self.imageArray[i];
        SelectPicCollectionViewCell *cell = (SelectPicCollectionViewCell*)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        mjPhoto.srcImageView = cell.imageView; //设置来源哪一个UIImageView
        [photos addObject:mjPhoto];
    }
    brower.photos = photos;
    brower.isShowDeleteButton = YES;
    brower.delegate = self;
    //3.设置默认显示的图片索引
    brower.currentPhotoIndex = indexPath.row;
    //4.显示浏览器
    [brower show];
}

#pragma mark - MJPhotoBrowserDelegate
//删除所选的照片用
-(void)photoBrowser:(MJPhotoBrowser *)photoBrowser didDeletePhotoAtIndex:(NSInteger)index
{
    if (index < self.imageArray.count) {
        UIImage *image = self.imageArray[index];
        [self.imageArray removeObject:image];
        [self.collectionView reloadData];
    }
}

#pragma mark - UIImagePickerControllerDelegate
//用户选中图片后的回调(这里为照相用)
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        ALAssetsLibrary *library  = [[ALAssetsLibrary alloc] init];
        [library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
            if (error) {
                // TODO: error handling
            } else {
                [library  assetForURL:assetURL resultBlock:^(ALAsset *asset) {
                    [self.imageArray insertObject:image atIndex:self.imageArray.count - 1];
                    [_collectionView reloadData];
                } failureBlock:^(NSError *error) {
                    
                }];
            }
        }];
    }
}
//TZImagePickerController选择照片后的回调(这里为相册用)
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos
{
    if (self.imageArray.count + photos.count > 10) {
        ShowMessage(@"您最多选择9张照片");
        return;
    }
    [self.imageArray removeObjectAtIndex:self.imageArray.count - 1];
    [self.imageArray addObjectsFromArray:photos];
    [self.imageArray addObject:[UIImage imageNamed:@"fankui"]];
    
    [_collectionView reloadData];
}

#pragma mark - action
- (void)rightBarButtonItemClick{
    NSLog(@"回收历史页");
    RecycleHistoryViewController * vc = [[RecycleHistoryViewController alloc] init];
    vc.title = @"回收历史";
    [self.navigationController pushViewController:vc animated:YES];
}

@end
